import json
import os
import sys

# 解析Entry.json文件
def ReadEntryInfo(entry: str):
    if not os.path.exists(entry):
        return '', '',''
    fo = open(entry, 'r')
    info = fo.read()
    fo.close()
    data = json.loads(info)
    titleName = ''
    partName = ''
    quality = '0'
    if 'title' in data:
        titleName = data['title'].strip()
    if ('page_data' in data) and ('part' in data['page_data']):
        partName = data['page_data']['part']
    if 'video_quality' in data:
        quality = str(data['video_quality'])
    return titleName, partName, quality

# 合成mp4文件
def CombineM4S(video, audio, output, ffmpgePath,option=''):
    if len(output) != 0 :
        if os.path.exists(output):
            os.remove(output)

        encoderOption = option
        if len(encoderOption) < 1:
            encoderOption = '-codec copy'

        cmd = '{0} -i {1} -i {2} {4} \'{3}\''.format(ffmpgePath, video, audio, output,encoderOption )
        os.system(cmd)

HelpInfo = '''
Help Info:
    Params: in='xxx' out='yyy'
    in: Bilibili Cache Folder
    out: Output Folder
        '''

VideoFileName = 'video.m4s'
AudioFileName = 'audio.m4s'
EntryFileName = 'entry.json'
FFMPEGFilePath = './ffmpeg'
FFMPEGOptions = ''

def ProcessFolder(root,dirs,files, outputDir):
    if len(files) < 1 or len(dirs) < 1 or not EntryFileName in files:
        return
    entryPath = os.path.join(root,EntryFileName)
    title,part,quality = ReadEntryInfo(entryPath)
    if not quality in dirs:
        print('Not Find Folder:' + os.path.join(root,quality))
        return
    # video data files
    videoPath = os.path.join(root,quality,VideoFileName)
    audioPath = os.path.join(root,quality,AudioFileName)
    if not os.path.exists(videoPath) or not os.path.exists(audioPath):
        print(f'Not Find Video File or Audio File:{videoPath} or {audioPath}')
        return
    # output path
    outputFolder = os.path.join(outputDir,title)
    if not os.path.exists(outputFolder):
        os.makedirs(outputFolder)
    outputFilePath = os.path.join(outputFolder,part) + '.mp4'
    if os.path.exists(outputFilePath):
        os.remove(outputFilePath)
    CombineM4S(videoPath,audioPath,outputFilePath,FFMPEGFilePath,FFMPEGOptions)
    return

def TransM4S2MP4():
    args = sys.argv
    if len(args) < 3:
        print(HelpInfo)
        return

    targetFolder = ''
    outputDir = ''

    for param in args:
        if param.startswith('in='):
            parts = param.split('=')
            if len(parts) > 1:
                targetFolder = parts[1]
        elif param.startswith('out='):
            parts = param.split('=')
            if len(parts) > 1:
                outputDir = parts[1]

    if len(outputDir) < 1 or len(targetFolder) < 1 :
        print(HelpInfo)
        return

    for root,dirs,files in os.walk(targetFolder):
        ProcessFolder(root,dirs,files,outputDir)

TransM4S2MP4()
